//
//  OTPTextfield.swift
//  SwiftuiUno
//
//  Created by hccc on 2023/11/30.
//

import SwiftUI
import Combine

struct OTPTextfield: View {
    var slot: Int = 4
    @Binding private var otp: String
    @FocusState private var isTextFieldFocused: Bool
    var onComplete: () -> ()
    
    init(slot: Int,
         otp: Binding<String>, 
         isTextFieldFocused: FocusState<Bool>,
         onComplete: @escaping () -> ()
    ) {
        self.slot = slot
        self._otp = otp
        self._isTextFieldFocused = isTextFieldFocused
        self.onComplete = onComplete
    }
    
    var body: some View {
        VStack {
            TextField("", text: $otp)
                .keyboardType(.numberPad)
                .onChange(of: otp, perform: { newValue in
                    if newValue.count > slot {
                        otp = String(newValue.prefix(slot))
                    } else if newValue.count == slot {
                        print("Entered OTP: \(newValue)")
                        self.onComplete()
                    }
                })
                .foregroundColor(.red)
                .opacity(0)
                .frame(height: 40)
                .overlay (
                    HStack(spacing: 10) {
                        ForEach(0..<slot, id: \.self) { index in
                            Text(index < otp.count ? String(otp[otp.index(otp.startIndex, offsetBy: index)]) : "•")
                                .font(.largeTitle)
                                .frame(width: 30, height: 40)
                                .foregroundStyle(Theme.color.title)
                                .multilineTextAlignment(.center)
                        }
                    }
                )
                .focused($isTextFieldFocused)
                .opacity(1) // 隐藏TextField
                .onTapGesture {
                    isTextFieldFocused = true
                }
        }
    }
}

//#Preview {
//    OTPInputView(slot: <#Int#>, otp: <#Binding<String>#>, isTextFieldFocused: <#FocusState<Bool>#>)
//}
